import { defineStore } from 'pinia'
import Notifier from 'src/helpers/Notifier'
import { api } from 'boot/axios'
import {LocalStorage} from 'quasar'
import { User } from 'src/models/user'
import qs from "qs";

export const authStore = defineStore('auth', {
  state: () => ({
    user: new User(LocalStorage.getItem('user') || null),
    accessToken: (LocalStorage.getItem('accessToken') || '')
  }),

  getters: {
    isAdmin: (state) => {
      return state.user?.is_admin
    },
    isHrManager: (state) => {
      return state.user?.is_hr_manager
    },
    isDirector: (state) => {
      return state.user?.is_director
    }
  },

  actions: {
    async login (form) {
      try {
        const response = await api.post('/login', qs.stringify(form))
        if (response) {
          this.accessToken = response.data.access_token
        }
        Notifier.success('Успешный логин')
        return true
      } catch (err) {
        Notifier.error('Неверный логин или пароль')

        console.error(err)
        return false
      }
    },
    logout () {
      this.user = null
      this.accessToken = ''
      LocalStorage.remove('accessToken')
      LocalStorage.remove('user')
    },
    async getUserSelf () {
      try {
        const response = await api.get('/admins/me/')
        this.user = new User(response.data)

        return this.user
      } catch (err) {
        Notifier.error('Ошибка при получении пользователя')

        console.error(err)
        return err
      }
    },
    async updateUserSelf (payload) {
      try {
        const response = await api.put('/admins/me', payload)

        this.user = new User(response.data)
        LocalStorage.set('user', this.user)

        Notifier.success('Профиль обновлен успешно')

        return this.user
      } catch (err) {
        Notifier.error('Ошибка при обновлении профиля')

        console.error(err)
        return err
      }
    },
  }
})
